#include "xml_core.h"
#include "main.h"

xml_core::xml_core()
{}

xml_core::xml_core(QString pathname,QObject *parent): QObject(parent),pathname(pathname)
{
    xmldoc.setFileName( pathname);

    if(xmldoc.open(QFile::ReadWrite|QFile::Text |QFile::Unbuffered))
    {
      //  xmlreader.setDevice(&xmldoc);
        xmlwriter.setDevice(&xmldoc);
    }
    else printf("%s xml doc open failed !",pathname);
  //  else {WARN->show_text("文件打开失败！");}

//    if(xmldoc.size()<500 && pathname!=ROOT_PATH+"used-times.xml")
//    {
//    xmldoc.remove();
//    QFileInfo fi(xmldoc.fileName());
//    QString fn=fi.fileName();
//    xmldoc.copy("/qt/BACKUP/"+fn,"/qt/sterilization/"+fn);
//    }
 write_changed=0;
     readxml();

}
void xml_core::readxml()
{
count=0;
//xmldoc.close();//重置读取位置
//xmldoc.open(QFile::ReadWrite|QFile::Text|QFile::Unbuffered);
xmldoc.seek(0);
xmlreader.setDevice(&xmldoc);

while(!xmlreader.atEnd())
{
    xmlreader.readNextStartElement();
    if((xmlreader.name()!="start_document")&&
            (xmlreader.tokenType()!=QXmlStreamReader::NoToken))
    {
 LIST[count].list_name=xmlreader.name().toString();
 LIST[count].list_value=xmlreader.readElementText();
 count++;     
     }
}
}

void xml_core::save()
{
    if( write_changed)
    {
 // xmldoc.resize(0);
 // xmldoc.remove();
  xmldoc.close();
  xmldoc.open(QFile::ReadWrite|QFile::Text  | QIODevice::Truncate);
  xmlwriter.setDevice(&xmldoc);
  xmlwriter.setAutoFormatting(true);
  xmlwriter.writeStartDocument();
  xmlwriter.writeStartElement("start_document");
   for(int i=0;i<count;i++ )  //
  {
       if( LIST[i].list_name=="") continue;
       else xmlwriter.writeTextElement(LIST[i].list_name,LIST[i].list_value);
   }
   xmlwriter.writeEndDocument();
   xmldoc.flush();//写回速度慢 40s
   write_changed=0;
    }
}


void xml_core::write(QString name,QString str)
{
    int num=indexof(name);
    write_changed=1;
    if(num==-1)
   {
    LIST[count].list_name=name;
    LIST[count].list_value=str;
    count++;
    }
    else LIST[num].list_value=str;

}



int xml_core::indexof(QString str)
{

   bool founded=0;
   int i=0;
    for(;i<count;i++)
    {
        if(LIST[i].list_name==str)
        {founded=1;break;}
    }
     return founded?i:-1;
}

QString xml_core::value(QString name)
{
    int num=indexof(name);
    return (num==-1)?"not found":QString(LIST[num].list_value);
}

int xml_core::stringtoint(QString str)
{
    int value;
    uint lg= str.length();
     if(str.startsWith('-'))
     {
     str= str.right(lg-1);
     value=0-str.toInt();
     }
     else value=str.toInt();
    return value;
}
